package top.milkbox.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.milkbox.service.PictureVerificationCodeService;
import top.milkbox.utils.GuoUtilsVerifyCode;

import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

@Slf4j
@Service
public class PictureVerificationCodeServiceImpl implements PictureVerificationCodeService {
    @Override
    public BufferedImage initPictureCode(HttpSession session) {
        log.debug("正在生成图片验证码...");
        int width = 140;
        int height = 55;
        //生成对应宽高的初始图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 将对应的图片传入，并传入宽高。在图片中添加字符和噪点，返回添加的字符
        String randomText = GuoUtilsVerifyCode.drawRandomText(width, height, image);

        // 打印验证码
        log.debug("生成的验证码：" + randomText);

        // 将验证码存入session域对象中
        session.setAttribute("pictureVerificationCode", randomText);
        // 返回图片
        return image;

    }

    @Override
    public Boolean check(HttpSession session, String code) {
        // 获取session中的域对象
        String sessionCode = (String) session.getAttribute("pictureVerificationCode");
        // 校验
        log.debug("用户输入的验证码：" + code + "，session中的验证码：" + sessionCode);
        if (code == null || !code.equalsIgnoreCase(sessionCode)) {
            // 验证码错误
            log.debug("校验失败");
            return false;
        }

        // 验证码正确
        // 及时销毁session中的验证码
        session.removeAttribute("pictureVerificationCode");
        log.debug("校验成功");
        return true;
    }
}
